package com.example.administrator.mvvm.module.user;

import android.arch.lifecycle.Observer;
import android.databinding.DataBindingUtil;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;

import com.example.administrator.mvvm.R;
import com.example.administrator.mvvm.databinding.ActivityUserBinding;
import com.example.administrator.mvvm.model.entity.GoodsEntity;
import com.example.administrator.mvvm.model.entity.UserEntity;
import com.trello.rxlifecycle2.components.support.RxAppCompatActivity;

import java.util.List;

/**
 * 用户信息页面
 */
public class UserActivity extends RxAppCompatActivity {
    //DataBinding用来绑定UI和数据
    ActivityUserBinding dataBinding;
    //用来处理用户信息相关的业务逻辑
    UserViewModel viewModel;

    GoodsAdapter adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        dataBinding = DataBindingUtil.setContentView(this, R.layout.activity_user);
        dataBinding.setLifecycleOwner(this);
        viewModel = new UserViewModel(getApplication());
        //将activity_user的UI与该ViewModel绑定
        dataBinding.setViewmodel(viewModel);

        //获取用户数据
        viewModel.getUserInfo();
        //监听请求结果
        viewModel.getUserLiveData().observe(this, new Observer<UserEntity>() {
            @Override
            public void onChanged(@Nullable UserEntity userEntity) {
                //设置控件上的数据显示
                dataBinding.setUser(userEntity);
            }
        });

        //recycleView
         adapter = new GoodsAdapter(this);
        dataBinding.rvList.setLayoutManager(new LinearLayoutManager(this));
        dataBinding.rvList.setAdapter(adapter);
        //获取商品数据
        viewModel.getGoods();
        //监听请求结果
        viewModel.getGoodsLiveData().observe(this, new Observer<List<GoodsEntity>>() {
            @Override
            public void onChanged(@Nullable List<GoodsEntity> goodsEntities) {
                adapter.setData(goodsEntities);
            }
        });
    }

}
